package com.example.goodsass.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.example.goodsass.common.BaseResponse;
import com.example.goodsass.common.BusinessException;
import com.example.goodsass.common.ErrorCode;
import com.example.goodsass.constans.enums.UserRole;
import com.example.goodsass.constants.UserConstants;
import com.example.goodsass.domain.User;
import com.example.goodsass.dto.user.UserEditDto;
import com.example.goodsass.dto.user.UserRegisterDto;
import com.example.goodsass.service.UserService;
import com.example.goodsass.vo.UserVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController("/user")
@Validated
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping(value = "/loginOrRegister")
    public BaseResponse<UserVO> loginOrRegister(@RequestBody UserRegisterDto userRegisterDto, HttpServletRequest request) {
        User dbUser = userService.lambdaQuery().eq(User::getUserAccount, userRegisterDto.getUserAccount()).one();
        String rawPassword = userRegisterDto.getPassword();
        String message;
        if (dbUser == null) {
            String salt = RandomUtil.randomString(16);
            String hashed = DigestUtil.sha256Hex(salt + rawPassword);
            User user = new User();
            user.setUserAccount(userRegisterDto.getUserAccount());
            user.setNickName("用户" + userRegisterDto.getUserAccount());
            user.setUserAvatar(UserConstants.DEFAULT_AVATAR);
            user.setPassword(hashed);
            user.setSalt(salt);
            user.setRoleName(UserRole.USER.getValue());
            userService.save(user);
            dbUser = user;
            message = "注册成功";
        } else {
            boolean isValid = DigestUtil.sha256Hex(dbUser.getSalt() + rawPassword)
                    .equals(dbUser.getPassword());
            message = "登录成功";
            if (!isValid) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "密码错误");
            }
        }
        request.getSession().setAttribute(UserConstants.USER_LOGIN_STATE, dbUser);
        return BaseResponse.success(BeanUtil.copyProperties(dbUser, UserVO.class), message);
    }

    @GetMapping(value = "/getLoginUser")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstants.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询 确保数据最新
        String userId = currentUser.getId();
        currentUser = userService.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return BaseResponse.success(BeanUtil.copyProperties(currentUser, UserVO.class));
    }

    @PostMapping(value = "/logout")
    public BaseResponse<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute(UserConstants.USER_LOGIN_STATE);
        return BaseResponse.success("退出成功");
    }

    @PostMapping(value = "/updateUserAvatar")
    public BaseResponse<String> updateUserAvatar(@RequestBody UserEditDto userEditDto, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(UserConstants.USER_LOGIN_STATE);
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        User user = new User();
        user.setId(currentUser.getId());
        if (!StrUtil.isBlankOrUndefined(userEditDto.getUserAvatar())) {
            user.setUserAvatar(userEditDto.getUserAvatar());
        }
        if (!StrUtil.isBlankOrUndefined(userEditDto.getNickName())) {
            user.setNickName(userEditDto.getNickName());
        }
        userService.updateById(user);
        request.getSession().setAttribute(UserConstants.USER_LOGIN_STATE, user);
        return BaseResponse.success("更新成功");
    }

    @PostMapping(value = "delUser")
    public int delUser(String userid, HttpServletRequest request) {
        UserVO currentUser = this.getLoginUser(request).getData();
        if (!currentUser.getRoleName().equals(UserRole.ADMIN.getValue())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有管理员才可以修改别人的资料");
        }
        return userService.delUser(userid);
    }

    @PostMapping(value = "updUser")
    public Boolean updUser(UserEditDto user, HttpServletRequest request) {
        UserVO currentUser = this.getLoginUser(request).getData();
        if (!currentUser.getRoleName().equals(UserRole.ADMIN.getValue())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有管理员才可以修改别人的资料");
        }
        User user1 = new User();
        user1.setId(currentUser.getId());
        return userService.updateById(user1);
    }

    @PostMapping(value = "insUserInAdmin")
    public Boolean insUserInAdmin(@RequestBody User user,HttpServletRequest request) {
        //校验了当前用户的权限
        userService.LoginUserCheck(request);
        //前端入参的校验
        if (userService.insUserCheck(user)){
            user.setUserAvatar("http://abluedog.fun:9001/useravatar/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_2025-04-12_145824_711.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=PFSbs4OUoZkC32Jv4KmZ%2F20250412%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250412T072135Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=ecbcd861a74fd15d7bcd1ead2ebf3b5b02aa1765f0972f17f4d4c6fecc69e5af");
            String salt = RandomUtil.randomString(16);
            String hashed = DigestUtil.sha256Hex(salt + user.getPassword());
            user.setPassword(hashed);
            user.setSalt(salt);
            return userService.save(user);
        }
        return false;
    }
}
